package dao;

import model.Owner;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OwnerDao {
    public void addOwner(Owner owner) throws Exception {
        Connection conn = DBUtil.getConnection();
        String sql = "INSERT INTO owner (id, name, phone) VALUES (?, ?, ?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, owner.getId());
        ps.setString(2, owner.getName());
        ps.setString(3, owner.getPhone());
        ps.executeUpdate();
        ps.close();
        conn.close();
    }

    public void updateOwner(Owner owner) throws Exception {
        Connection conn = DBUtil.getConnection();
        String sql = "UPDATE owner SET name=?, phone=? WHERE id=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, owner.getName());
        ps.setString(2, owner.getPhone());
        ps.setInt(3, owner.getId());
        ps.executeUpdate();
        ps.close();
        conn.close();
    }

    public void deleteOwner(int id) throws Exception {
        Connection conn = DBUtil.getConnection();
        String sql = "DELETE FROM owner WHERE id=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, id);
        ps.executeUpdate();
        ps.close();
        conn.close();
    }

    public Owner getOwnerById(int id) throws Exception {
        Connection conn = DBUtil.getConnection();
        String sql = "SELECT * FROM owner WHERE id=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, id);
        ResultSet rs = ps.executeQuery();
        Owner owner = null;
        if (rs.next()) {
            owner = new Owner(rs.getInt("id"), rs.getString("name"), rs.getString("phone"));
        }
        rs.close();
        ps.close();
        conn.close();
        return owner;
    }

    public List<Owner> getAllOwners() throws Exception {
        Connection conn = DBUtil.getConnection();
        String sql = "SELECT * FROM owner";
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        List<Owner> list = new ArrayList<>();
        while (rs.next()) {
            list.add(new Owner(rs.getInt("id"), rs.getString("name"), rs.getString("phone")));
        }
        rs.close();
        st.close();
        conn.close();
        return list;
    }

    // 查询业主拥有的所有房屋
    public List<String> getHouseIdsByOwnerId(int ownerId) throws Exception {
        Connection conn = DBUtil.getConnection();
        String sql = "SELECT houseId FROM own WHERE ownerId=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, ownerId);
        ResultSet rs = ps.executeQuery();
        List<String> houseIds = new ArrayList<>();
        while (rs.next()) {
            houseIds.add(rs.getString("houseId"));
        }
        rs.close();
        ps.close();
        conn.close();
        return houseIds;
    }
}